package com.xzg.gulimall.seckill.scheduled;

import com.xzg.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


/*秒杀商品定时上架，
每天晚上3点，上架最近三天秒杀的商品
当天00：00：00 - 23：59：59
明天00：00：00 - 23：59：59
后天00：00：00 - 23：59：59
 */
@EnableScheduling
@EnableAsync
@Service
@Slf4j
public class SeckillSkuScheduled {
    @Autowired
    SeckillService seckillService;
    @Autowired
    RedissonClient redissonClient;
    private final String upload_lock = "seckill:ipload:lock";
    //TODO:幂等性处理
    @Scheduled(cron = "*/3 * * * * ?")
    public void uploadSeckillSkuLates3Days()
    {
        //重复上架无需处理
        log.info("上架秒杀信息");
        //分布式锁
        RLock lock = redissonClient.getLock(upload_lock);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            seckillService.uploadSeckillSkuLatest3Days();
        }finally {
            lock.unlock();
        }

    }
}
